//
//  ARVideoFlowViewModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/21.
//

import Foundation

class ARVideoFlowViewModel {
    
    // MARK: - Property
    
    private var _dataSource: [ARVideoWorkModel] = []
    var dataSource: [ARVideoWorkModel] {
        _dataSource
    }
    
    /// 刷新comment
    var reloadCommentCallback: ((_ index: Int, _ videoModel: ARVideoWorkModel) -> Void)?
    
    // MARK: - Action
    
    func fetchVideoList(_ completion: @escaping (Error?) -> Void) {
        ARDataCenter.default.fetchVideoWorkList { [weak self] list, err in
            if let err = err {
                completion(err)
                return
            }
            guard let list = list else {
                completion(ARRequestError.modelConvertError(error: nil))
                return
            }
            
            // 加载本地
//            ARHelper.afterAsyncInMainQueue {
//                self?._dataSource.removeAll()
//                let first = list.first!
////                first.videoUrl = "http://test-agilecdn.livchat.me/AquaRaft/vedio/9.mp4?Expires=1721663199&OSSAccessKeyId=LTAI5tNPNT6g1inCHkxgcUGz&Signature=YDVCuorCEvhrVCKmbLP91gLeJwA%3D"
//                self?._dataSource.append(contentsOf: list)
//                self?._dataSource.append(first)
//                completion(nil)
//            }
            
            // 加载远程
            // 获取数据
            var paths: [String] = []
            for model in list {
                paths.append(model.shortPath)
            }
            ARMediaConvertPathRequest().convertVideoPathsToUrls(paths) { result in
                switch result {
                case .faild(let err):
                    completion(err)
                case .successWithoutResponse:
                    completion(ARRequestError.modelConvertError(error: nil))
                case .success(let model):
                    // 数据一定是一一对应的
                    self?._dataSource.removeAll()
                    for i in 0..<model.count {
                        let videoWork = list[i]
                        let url = model[i]

                        videoWork.videoUrl = url
                        self?._dataSource.append(videoWork)
                    }
                    completion(nil)
                }
            }
        }
        
    }
    
    func postTextComment(_ comment: String, videoWork: ARVideoWorkModel, completion: @escaping (Error?) -> Void) {
        guard let userId = ARUserManager.shared.userId, let userModel = ARUserManager.shared.userModel else {
            return
        }
        
        let commentModel = ARCommentModel()
        commentModel.commentType = .text
        commentModel.comment = comment
        // 设置 id / authorid
        commentModel.authorId = userId
        commentModel.id = "commnet_\(userId)_\(Date().timeIntervalSince1970)"
        
        var comments = videoWork.comments ?? []
        comments.append(commentModel)
        commentModel.author = userModel
        videoWork.comments = comments
        
        // 回调
        ARHelper.afterAsyncInMainQueue {
            completion(nil)
            
            // 去除comment
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5.0) { [self] in
                var comments = videoWork.comments ?? []
                if comments.isEmpty {
                    return
                }
                guard let index = dataSource.firstIndex(videoWork) else {
                    return
                }
                comments.removeAll(where: { $0 == commentModel})
                videoWork.comments = comments
                reloadCommentCallback?(index, videoWork)
            }
        }
    }
    
    func followUser(_ userId: String, completion: @escaping (Error?) -> Void) {
        // 因为 datacenter 获取的数据都是对象，所以在datacenter中修改之后，其他地方也会是最新的数据
        ARDataCenter.default.followOrUnfollowUser(userId, followOrUnfollow: true) { err in
            completion(err)
        }
    }
    
    func likeOrUnlikeVideoWork(_ videoWork: ARVideoWorkModel, completion: @escaping (Error?) -> Void) {
        ARDataCenter.default.likeOrUnlikeVideoWork(videoWork.id, like: !videoWork.isLike) { err in
            ARHelper.afterAsyncInMainQueue {
                completion(err)
            }
        }
    }
    
}
